<?php
/**
 * 解析退货订单-数据入库
 *（Logic）
 */
namespace App\Logic\Amazon\Api\Parse;

use App\Models\Amazon\AmazonOrder;
use App\Models\Amazon\FbaCustomerReturn;
use App\Models\Basics\AmazonCountry;
use App\Models\Product\ProductAmazonSku;
class GetFbaFulfillmentCustomerReturnsData
{
    public static function exe($lines,$accountId){
        if(!$accountId)return 2;
        if(!is_array($lines))return 2;
        $i = 0;
        $count = 0;
        try{
            foreach($lines as $line){
                $flag = self::_addCustomerReturn($line,$accountId);
                $flag && $count++;
                $i++;
            }
        }catch (\Exception $e){
            report($e);
        }
        return $i == $count ? 1 : 2;
    }

    /**
     * Amazon-fba客户退货
     * @param $line
     * @param $accountId
     * @return bool
     */
    private static function _addCustomerReturn($line,$accountId){
        if(!$line['sku'])return true;
        $returnDate = gmdate('Y-m-d H:i:s',strtotime($line['return-date']));
        $count = FbaCustomerReturn::query()
            ->where('account_id',$accountId)
            ->where('return_date',$returnDate)
            ->where('order_id',$line['order-id'])
            ->where('sku',$line['sku'])
            ->where('quantity',$line['quantity'])
            ->where('fulfillment_center_id',$line['fulfillment-center-id'])
            ->count();
        if($count > 0)return true;
        $order = AmazonOrder::query()->where('amazon_order_id',$line['order-id'])->first();
        $countryId = AmazonCountry::getCountryIdByMarketplaceId($order->marketplace_id ?? 0);
        $pSkuId = ProductAmazonSku::query()->where('seller_sku',$line['sku'])->value('psku_id');
        $re = FbaCustomerReturn::query()->create([
            'account_id' => $accountId,
            'country_id' => $countryId ?: 0,
            'psku_id' => $pSkuId ?: 0,
            'return_date' => $returnDate, //退货时间
            'purchase_date' => $order->purchase_date ?? null, //下单时间
            'order_id' => $line['order-id'],
            'sku' => $line['sku'],
            'asin' => $line['asin'],
            'fnsku' => $line['fnsku'],
            'quantity' => $line['quantity'],
            'detailed_disposition' => $line['detailed-disposition'], //处置方式(SELLABLE(可二次销售的), DEFECTIVE(产品存在质量问题的/瑕疵品), DAMAGED(损坏的), CUSTOMER_DAMAGED(客户损坏的), CARRIER_DAMAGED(运输损坏的))
            'fulfillment_center_id' => $line['fulfillment-center-id'],
            'reason' => $line['reason'] ?: null, //主要退货原因
            'customer_comments' => $line['customer-comments'] ?: null, //退货评论
            'status' => !$line['customer-comments'] ? 2 : 0, //统计状态(0:未统计 1:已统计 2:无评论)
        ]);
        return !$re ? false : true;
    }
}
